package com.weds.frame.domain.config.mybatis;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.sql.Statement;
import java.util.Objects;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/3/20 13:06
 */
@Component
@ConditionalOnProperty(name = "log.sql-active", matchIfMissing = false, havingValue = "true")
@Intercepts({
        @Signature(
                type = StatementHandler.class,
                method = "query",
                args = {Statement.class, ResultHandler.class}),
        @Signature(type = StatementHandler.class, method = "update", args = {Statement.class})
})
@Slf4j
public class SqlLogInterceptor implements Interceptor {
    @Value("${log.slow-sql-limit}")
    private Integer slowSqlLimit;
    @Value("${log.active}")
    private Boolean logActive;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Long b = System.currentTimeMillis();
        String sql = ((StatementHandler) invocation.getTarget()).getBoundSql().getSql();
        Object obj = invocation.proceed();
        if(Objects.isNull(logActive) || !logActive)
            return obj;
        if (Objects.nonNull(slowSqlLimit) && (System.currentTimeMillis() - b) > slowSqlLimit) {
            log.error("出现慢sql，耗时 {}ms, sql: {}", (System.currentTimeMillis() - b), sql.replaceAll("\\\n", ""));
            return obj;
        }
        log.info("执行sql耗时: {}ms , sql: {}", (System.currentTimeMillis() - b), sql.replaceAll("\\\n", ""));
        return obj;
    }
}
